<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e">
    </ex_super_table_page>

    <!-- 处理 -->
    <handleDialog ref="handleDialog" @success="reload"></handleDialog>

    <!-- 认领 -->
    <ex_super_dialog_form ref="claimDialog" v-bind="claimDialog" @afterSubmitSuccess="reload()" />

    <!-- 审核 -->
    <ex_super_dialog_form ref="examineDialog" v-bind="examineDialog" @afterSubmitSuccess="reload()" />
  </div>
</template>
<script>
import handleDialog from './dialog/handle_dialog.vue'
import business_function from "@/common/business_function"

import superTablePageFunction from '@/mixin/super-table-page-function';
import emitOnFunction from '@/mixin/emit-on-function';

import page_table_model_manage from '@/mixin/page_table_model_manage';
let emitKey = 'returngood>manage'
export default {
  title: 'label_returnGood_order_list',
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: { handleDialog },
  data() {
    const status_enum = (this.$enumOptions['ReturnOrderStatusEnum'] ? this.$enumOptions['ReturnOrderStatusEnum'].filter(it => !['TO_BE_CLAIMED', 'CLAIMED',
      'INSPECTIONING', 'WAIT_PUTAWAY', 'PARTIAL_PUTAWAY',
      'UNDER_REVIEW', 'AUDIT_FAILURE', 'DESTROYED',
    ].includes(it)) : [])
    status_enum.splice(status_enum.indexOf("PROCESSING"), 1)
    status_enum.splice(status_enum.indexOf("COMPLETED"), 0, "PROCESSING")
    return {
      statusRadioGroup: this.$enumOptions['ReturnOrderStatusEnum'],
      selection: [],
      storeList: [],
      option: {
        search: {
          default: { status: "" },
          resetFieldFun: (def, org) => { def.status = org.status; return def },
          model: [
            {
              key: 'status',
              label: 'label_status',
              itemClass: "w_fill",
              enum: 'ReturnOrderStatusEnum',
              type: 'select',
              render: (h, { data }) => {
                const list = this.statusRadioGroup
                  .map(it => (
                    <el-radio-button key={it} label={it}>
                      {this.$enumShow(it, 'ReturnOrderStatusEnum')}
                    </el-radio-button>
                  ))
                return (<el-radio-group value={data.status}
                  onInput={e => {
                    this.$set(data, 'status', e)
                    this.$refs.SuperTablePage.loadDataForSearch()
                  }}>
                  <el-radio-button key="" label="">
                    {this.$tt("label_all")}
                  </el-radio-button>
                  {list}
                </el-radio-group>
                )
              }
            },

            { label: "label_return_order_code", key: "orderCodeList",placeholder:"tip_input_can_comma_separated", },
            { label: "label_warehouse", key: "warehouseId", type: "base_warehouse_select" },
            { label: "label_track_code", key: "trackNumberList", placeholder:"tip_input_can_comma_separated", },
            { label: "label_is_unclaimed", key: "isUnclaimed", type: "select", enum: 'YesOrNoEnum' },
            { label: "label_return_type", key: "returnType", type: "select", enum: 'ReturnRetTypeEnum' },
            { label: "label_platform", key: "platformCode", type: "select", enum: 'SrmOrderTypeEnum' },
            {
              label: "label_time_type", key: 'queryTimeType', type: 'select', enum: 'ReturnTimeQueryTypeEnum', fold: true,
              on: {
                change: (e) => {
                  if(!e){
                    this.$set(this.$refs.SuperTablePage.$refs.search.getData(), "timeFrom", null)
                    this.$set(this.$refs.SuperTablePage.$refs.search.getData(), "timeTo", null)
                  }
                }
              },
            },
            {
              key: 'timeFrom', label: "label_time_range", fold: true, type: 'date-picker', attrs: { type: 'datetime' },
              render: (h, { data, item }) => {
                const value = data[item.key]
                const limitKey = 'timeTo'
                const limitValue = data[limitKey]
                const disabledKey = 'queryTimeType'
                const disabledValue = !data[disabledKey]
                return (<ex_super_input value={value} disabled={disabledValue}  onInput={e => this.$set(data, item.key, e)} type="date-picker" placeholder="label_start_time"
                  attrs={{ type: 'datetime' }}
                  pickerOptions={{
                    disabledDate: date => { return limitValue ? (limitValue < date.getTime()) : false }
                  }}
                />)
              }

            },
            {
              key: 'timeTo', label: "~", fold: true, type: 'date-picker', attrs: { type: 'datetime' },
              render: (h, { data, item }) => {
                const value = data[item.key]
                const limitKey = 'timeFrom'
                const limitValue = data[limitKey]
                const disabledKey = 'queryTimeType'
                const disabledValue = !data[disabledKey]

                return (<ex_super_input value={value} disabled={disabledValue} onInput={e => this.$set(data, item.key, e)} type="date-picker" placeholder="label_end_time"
                  attrs={{ type: 'datetime', 'default-time': '23:59:59' }}
                  pickerOptions={{
                    disabledDate: date => { return limitValue ? (limitValue > date.getTime()) : false }
                  }}
                />)
              }
            },
            // { label: "label_is_destroy", key: "destroy", type: "select", enum: 'YesOrNoEnum', fold: true, },
            { label: "label_is_unpack", key: "needUnpacking", type: "select", enum: 'YesOrNoEnum', fold: true, },
            { label: "front_label_pack_pallet_code", key: "packageCode", fold: true, },
            { label: "label_platform_code", key: "platformOrderNo",fold: true,  },
            { label: "label_ec_platform_code", key: "ecommerceOrderNo",fold: true,  },
            {
              key: 'productId',
              label: 'label_return_goods_product',
              type:'select',
              fold: true,
              url:'/fms-api/client/CustomerProductQueryClientRpc/getReturnProduct.json',
              option:item=>({ label: this.$formatNameCode(item.productName, item.productCode), value: item['id'] })
            },
          ],
        },
        actionExtra: [
          {
            label: 'label_new_returnGood_order', attrs: { type: "primary" },
            click: () => {
              this.$router.push({ path: './returngood_operate', query: { emitKey, } })
            }
          },
          // { label: 'label_operate_log_report', click: this.exportExcel },
        ],
        table: {
          url: this.$url['oms/ReturnOrderList'],
          model: this.init_table_model(),
        },
      },
      claimDialog: {
        customClass: 'dialog_extra',
        detailUrl: this.$url['oms/ReturnOrderDetail'],
        submitUrl: this.$url['oms/ReturnOrderSubmitClaim'],
        detailDataHandle: (data) => {
          // 客户ID为-1时 标识无主货 无客户
          if (data.customerId === -1) {
            data.customerId = ''
          }
          // 详情里商品id 和客户id同样的逻辑
          data.detailList.forEach(item => {
            if (item.customerId === -1) {
              item.customerId = ''
            }
            if (item.skuId + '' === '-1') {
              item.skuId = ''
              item.notSkuId = true
            }
          })
          return data
        },
        submitDataHandle: (data) => {
          data.returnOrderId = data.id
          return data
        },
        form: {
          itemClass: "form_item_small", inputClass: "form_input_small",
          formClass: "flex_row_wrap",
          default: {
          },
          model: [

            { key: 'trackingNumber', label: 'label_returnGood_track_code', formType: "text" },
            { key: 'warehouseName', label: 'label_returnGood_warehouse', formType: "text", formatter: (r, c, v, i) => this.$formatNameCode(v, r.warehouseCode), },
            { key: 'itemsNumber', label: 'label_sku_count', formType: "text", },
            {
              key: 'order_photo', label: 'label_order_photo', itemClass: 'w_fill',
              render: (h, { data }) => {
                if (!data.attachedList) return
                const list = data.attachedList.map(p => p.filePath)
                return (<div class="flex_row_wrap">
                  {list.map(it => (<ex_image_view style="width: 7rem;height: 7rem; margin-right:10px" src={it} lazy fit="fill" preview-src-list={list} />))}
                </div>)
              }
            },
            // {
            //   key: 'warehouse_photo', label: 'label_warehouse_photo', itemClass: 'w_fill',
            //   render: (h, { data }) => {
            //     if (!data.attachedList) return
            //     const list = data.attachedList.filter(it => it.type != 'RETURN_IMAGE').map(p => p.filePath)
            //     return (<div class="flex_row_wrap">
            //       {list.map(it => (<ex_image_view style="width: 7rem;height: 7rem; margin-right:10px" src={it} lazy fit="fill" preview-src-list={list} />))}
            //     </div>)
            //   }
            // },
            // {
            //   key: 'customerId', label: 'label_claim_customer', keyExtra: { customerCode: 'customerCode', customerName: 'customerName' },
            //   render: (h, { data }) => {
            //     return (
            //       <common_customer_choose value={data.customerId}
            //         clearable={false}
            //         onChangeItem={e => {
            //           if (!e) e = { customerId: null, customerCode: null, customerName: null }
            //           this.$set(data, "customerId", e.customerId)
            //           //重新选择客户后 商品需要重新关联
            //           data.detailList.forEach(it => {
            //             this.$set(it, "customerId", e.customerId)
            //             this.$set(it, "skuId", '')
            //           })
            //           data.customerCode = e.customerCode
            //           data.customerName = e.customerName
            //         }}
            //       ></common_customer_choose>
            //     )
            //   }

            // },
            {
              key: 'attachmentParams', label: 'label_claim_voucher',
              render: (h, { data }) => {
                return (<ex_super_upload
                  value={data.attachmentParams}
                  limit={3}
                  type="file"
                  onIsUploadChange={e => {
                    this.isUploadClaim = e
                  }}
                  onInput={e => {
                    e.map(it => {
                      it.fileType = it.fileExt
                      return it
                    })
                    this.$set(data, 'attachmentParams', e)
                  }}
                >
                </ex_super_upload>)
              }
            },
            {
              key: 'detailList',
              label: 'label_sku_specification',
              itemClass: "w_fill",
              inputClass: "w_fill",
              formType: "table",
              model: [
                { key: 'returnSkuCodeList', label: 'label_return_order_sku_code', 'min-width': 140, 'show-overflow-tooltip': true, formatter: (r, c, v) => v?v.join(','):''},
                { key: 'isAbnormal', label: 'label_is_abnormal', 'width': 120, formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum") },
                { key: 'skuReturnQuantity', label: 'label_return_order_count', 'width': 120, 'show-overflow-tooltip': true, },

                {
                  key: 'returnHandlingMethod', label: 'label_do_with_method', 'min-width': 160,
                  renderHeader: (h, { column, $index }) => (<span class="table-require">{column.label}</span>),
                  render: (h, { row, index }) => {
                    return (
                      <el-form-item
                        prop={`detailList.${index}.returnHandlingMethod`}
                        rules={this.ruleNoEmpty}
                      >
                        <ex_select_auto
                          class="w_fill"
                          enum='SkuReturnMethodEnum'
                          value={row.returnHandlingMethod}
                          onInput={value => {
                            this.$set(row, 'returnHandlingMethod', value)
                          }}
                        >
                        </ex_select_auto>
                      </el-form-item>)
                  }
                },
                {
                  key: 'skuOnlyCode', label: 'label_associated_sku', 'min-width': 160,
                  renderHeader: (h, { column, $index }) => (<span class="table-require">{column.label}</span>),
                  render: (h, { row, index }) => {
                    let show = this.$tt("tip_please_select_first_customer")
                    if (!row.notSkuId) {
                      return '—'
                    }
                    if (row.customerId) {
                      show = (
                        <sku_selec_input
                          value={row.skuId}
                          customerId={row.customerId}
                          clearable={false}
                          onChangeItem={value => {
                            if (!value) value = { id: null, skuOnlyCode: null }
                            this.$set(row, 'skuId', value.id)
                            this.$set(row, 'associatedCommodityCode', value.skuOnlyCode)
                          }}
                        />
                      )
                    }
                    return (<el-form-item prop={`detailList.${index}.associatedCommodityCode`}
                      rules={this.ruleNoEmpty}
                    >
                      {show}
                    </el-form-item>)
                  }
                },
                {
                  key: 'sku_photo', label: 'label_sku_photo', 'min-width': 140,
                  render: (h, { row }) => {
                    if (!row.attachedList) return
                    const list = row.attachedList.map(p => p.filePath)
                    return (<div class="flex_row_wrap">
                      {list.map(it => (<ex_image_view style="width: 7rem;height: 7rem;margin:0 5px" src={it} lazy fit="fill" preview-src-list={list} />))}
                    </div>)
                  }
                },
                // {
                //   key: 'warehouse_photo', label: 'label_warehouse_photo', 'min-width': 140,
                //   render: (h, { row }) => {
                //     if (!row.attachedList) return
                //     const list = row.attachedList.filter(it => it.type != 'RETURN_IMAGE').map(p => p.filePath)
                //     return (<div class="flex_row_wrap">
                //       {list.map(it => (<ex_image_view style="width: 7rem;height: 7rem;margin-right:10px" src={it} lazy fit="fill" preview-src-list={list} />))}
                //     </div>)
                //   }
                // },
              ],
            },

          ],
          rules: {
            'customerId': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
            'attachmentParams': [{ required: true, type: "array", message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
          },
        }
      },
      examineDialog: {
        customClass: 'dialog_extra',
        detailUrl: this.$url['oms/ReturnOrderDetail'],
        submitUrl: this.$url['oms/ReturnOrderAudit'],
        submitDataHandle: (data) => {
          return {
            returnOrderId: data.id,
            reviewStatus: data.reviewStatus,
            reviewReason: data.reviewReason,
          }
        },
        form: {
          itemClass: "form_item_mini", inputClass: "form_input_small",
          formClass: "flex_row_wrap",
          default: {
            reviewStatus: "APPROVED",
          },
          model: [
            { key: 'trackingNumber', label: 'label_returnGood_track_code', formType: "text" },
            { key: 'warehouseName', label: 'label_returnGood_warehouse', formType: "text", formatter: (r, c, v, i) => this.$formatNameCode(v, r.warehouseCode), },
            { key: 'itemsNumber', label: 'label_sku_count', formType: "text" },
            {
              key: 'order_photo', label: 'label_order_photo', itemClass: 'w_fill',
              render: (h, { data }) => {
                if (!data.attachedList) return
                const list = data.attachedList.map(p => p.filePath)
                return (<div class="flex_row_wrap">
                  {list.map(it => (<ex_image_view style="width: 7rem;height: 7rem;margin-right:10px" src={it} lazy fit="fill" preview-src-list={list} />))}
                </div>)
              }
            },
            { key: 'claimCustomerName', label: 'label_claim_customer', formType: "text", formatter: (r, c, v, i) => this.$formatNameCode(v, r.claimCustomerCode) },
            { key: 'unclaimedClaimType', label: 'label_claim_type', formType: "text", formatter: (r, c, v, i) => this.$enumShow(v, "ReturnOrderUnclaimedClaimTypeEnum") },
            { key: 'claimTiem', label: 'label_claim_time', formType: "text", formatter: (r, c, v, i) => this.$dateFormat(v) },
            {
              key: 'detailList', label: 'label_sku_specification', itemClass: "w_fill", inputClass: "w_fill", formType: "table",
              model: [
                { key: 'returnSkuCodeList', label: 'label_return_order_sku_code', 'min-width': 140, 'show-overflow-tooltip': true,formatter: (r, c, v) => v?v.join(','):'' },
                { key: 'isAbnormal', label: 'label_is_abnormal', 'width': 120, formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum") },
                { key: 'returnHandlingMethod', label: 'label_do_with_method', 'width': 140, 'show-overflow-tooltip': true, },
                { key: 'skuOnlyCode', label: 'label_associated_sku', 'width': 140, 'show-overflow-tooltip': true, },
                { key: 'skuReturnQuantity', label: 'label_return_order_count', 'width': 130, 'show-overflow-tooltip': true, },
                {
                  key: 'sku_photo', label: 'label_sku_photo', 'min-width': 140,
                  render: (h, { row }) => {
                    if (!row.attachedList) return
                    const list = row.attachedList.map(p => p.filePath)
                    return (<div class="flex_row_wrap">
                      {list.map(it => (<ex_image_view style="width: 7rem;height: 7rem;manage:0 5px" src={it} lazy fit="fill" preview-src-list={list} />))}
                    </div>)
                  }
                }
              ],
            },

            {
              key: 'reviewStatus',
              label: 'label_audit_status',
              type: 'select',
              enum: 'OmsReturnUnclaimedReviewStatusEnum',
              listHandler: (list) => list.filter(it => !["UNDER_REVIEW", "CANCEL"].includes(it))
            },
            { key: 'reviewReason', label: 'label_audit_reason', },
          ],
          rules: {
            'reviewStatus': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
          },
        }
      },
    };
  },
  methods: {
    option_table_model() {
      return [
      { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },
        {
          key: 'code', label: 'label_return_order_code', 'show-overflow-tooltip': true,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!code) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate extra_barcode_image extra_text_align='center'
              value={code}
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        { key: 'productName', label: 'label_return_goods_product', 'show-overflow-tooltip': true,formatter: (r, c, v, i) => this.$formatNameCode(v, r.productCode) },
        { key: 'warehouseName', label: 'label_warehouse', 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$formatNameCode(v, r.warehouseCode) },

        {
          key: 'trackingNumber', label: 'label_track_code', 'show-overflow-tooltip': true,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!row[column.property]) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate extra_barcode_image extra_text_align='center'
              value={code}
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        { key: 'shopId', label: 'label_platform_store', 'show-overflow-tooltip': true, },
        {
          key: 'customerTrackingNumber', label: 'label_customer_track_code', 'show-overflow-tooltip': true,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!row[column.property]) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate extra_barcode_image extra_text_align='center'
              value={code}
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        { key: 'status', label: 'label_status', formatter: (r, c, v, i) => this.$enumShow(v, "ReturnOrderStatusEnum") },
        { key: 'isUnclaimed', label: 'label_is_unclaimed', formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum") },
        { key: 'gmtCreate', label: 'label_create_time', width: 140, formatter: (r, c, v, i) => this.$dateFormat(v) },
        { key: 'receiveTime', label: 'label_receiving_time', width: 140, formatter: (r, c, v, i) => this.$dateFormat(v) },
        { key: 'acceptTime', label: 'label_inspection_time', width: 140, formatter: (r, c, v, i) => this.$dateFormat(v) },
        { key: 'putawayTime', label: 'label_tms_complete_date', width: 140, formatter: (r, c, v, i) => this.$dateFormat(r.putawayTime||r.destroyTime) },
        { key: 'needDeleteQty', label: 'label_need_delete_qty', 'show-overflow-tooltip': true, },
        { key: 'needUnpacking', label: 'label_is_unpack', formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum") },

        { key: 'platformName', label: 'label_platform', 'show-overflow-tooltip': true, },
        {
          key: 'platformOrderNo', label: 'label_platform_code', 'show-overflow-tooltip': true,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!row[column.property]) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate extra_barcode_image extra_text_align='center'
              value={code}
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        { key: 'returnType', label: 'label_return_type', formatter: (r, c, v, i) => this.$enumShow(v, "ReturnRetTypeEnum") },
        {
          key: 'packageCode', label: 'front_label_pack_pallet_code', 'show-overflow-tooltip': true,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!row[column.property]) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate extra_barcode_image extra_text_align='center'
              value={code}
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        {
          key: 'ecommerceOrderNo', label: 'label_ec_platform_code', 'show-overflow-tooltip': true,
          render: (h, { row, column }) => {
            const code = row[column.property]
            if (!row[column.property]) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate extra_barcode_image extra_text_align='center'
              value={code}
              data_type={column.property} data_id={row.id}
            />)
          },
        },
        {
          type: 'operate', width: 160,
          operate: [
            {
              label: "label_handle",
              click: row => this.clickHandle(row),
              if: row => row.actionCodes ? row.actionCodes.includes('CHARGE') : true,
            },
            {
              label: "label_claim",
              if: row => row.actionCodes ? row.actionCodes.includes('CLAIM') : true,
              click: (row) => {
                this.$refs.claimDialog.showNew({
                  title: this.$tt("label_ownless_claim"),
                  params: {
                    id: row.id
                  },
                })
              }
            },
            {
              label: "label_examine",
              if: row => row.actionCodes ? row.actionCodes.includes('AUDIT') : true,
              click: (row) => {
                this.$refs.examineDialog.showNew({
                  title: this.$tt("label_ownless_examine"),
                  params: {
                    id: row.id
                  },
                })
              }
            },
            {
              label: "label_edit",
              if: row => row.actionCodes ? row.actionCodes.includes('EDIT') : true,
              click: (row) => {
                this.$router.push({
                  path: './returngood_operate', query: { id: row.id, edit: true, emitKey }
                })
              }
            },
            {
              label: 'label_cancel_order',
              type: "confirm-button",
              url: this.$url['oms/ReturnOrderCancel'],
              message: 'text_confirm_sure_cancel_order',
              buttonClass: "button_text_danger",
              confirmButtonType: 'danger',
              urlType: 'form',
              if: row => row.actionCodes ? row.actionCodes.includes('CANCEL_ORDER') : true,
              params: (row) => {
                return { id: row["id"] }
              }, done: ['tip', 'reload']
            },
            {
              label: 'label_cancel_claim',
              type: "confirm-button",
              url: this.$url['oms/ReturnOrderCancelClaim'],
              message: 'text_confirm_sure_cancel_claim',
              buttonClass: "button_text_danger",
              confirmButtonType: 'danger',
              urlType: 'form',
              params: (row) => {
                return { returnOrderId: row["id"] }
              }, done: ['tip', 'reload'],
              if: row => row.actionCodes ? row.actionCodes.includes('CANCEL_CLAIM') : true,
            },
            {
              label: "label_tms_driver_view",
              click: (row) => this.clickDetail(row)
            },

          ]
        }
      ]
    },
    clickDetail(row) {
      this.$router.push({
        path: './returngood_detail', query: { id: row.id,code:row.code }
      })
    },
    exportExcel() {
      const searchParams = this.$refs.SuperTablePage.getSearchFormData()
      delete searchParams.importTime
      delete searchParams.confirmTime
      business_function.confirmOperateBaseSelectOrForm.call(this, {
        data: searchParams,
        model: this.option.search.model,
        mustData: true,
        callback: (selection, data) => {
          const idList = this.selection.map(item => item.id)
          this.$functionCommon({
            url: "/oms-api/refund/ReturnOrderRpc/orderExport.json",
            data: { ...data, idList },
            type: 'form',
          })
        }
      })
    },
    clickHandle(row) {
      this.$refs.handleDialog.show({ row, emitKey })
    },
  }
};

</script>
<style></style>
